/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package le.grand.ui;

import java.awt.Graphics;
import java.awt.JobAttributes;
import java.awt.PageAttributes;
import java.awt.PrintJob;
import java.awt.print.PrinterException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import le.grand.OrderInTheHouse;
import dnl.confij.apps.ApplicationConfiguration;
import dnl.ui.FileChooserUtils;
import dnl.util.ui.WindowUtils;

/**
 * 
 * @author daniel
 */
public class LeGrandFrame extends javax.swing.JFrame {
	File selectedFile;
	List<JTextArea> jtas = new ArrayList<>();
	private ApplicationConfiguration applicationConfiguration;
	/**
	 * Creates new form LeGrandFrame
	 */
	public LeGrandFrame() {
		initComponents();
		applicationConfiguration = new ApplicationConfiguration("le.grand");
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        outputTA = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        fileSelectionJB = new javax.swing.JButton();
        fileTF = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        printJB = new javax.swing.JButton();
        maxNameSizeTF = new javax.swing.JTextField();
        jTabbedPane1 = new javax.swing.JTabbedPane();

        outputTA.setColumns(20);
        outputTA.setFont(new java.awt.Font("DejaVu Sans Mono", 0, 11)); // NOI18N
        outputTA.setRows(5);
        jScrollPane1.setViewportView(outputTA);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("לאיילת החמודה ... אל תעבדי קשה מדי");

        jPanel1.setPreferredSize(new java.awt.Dimension(56, 56));

        fileSelectionJB.setText("בחר קובץ");
        fileSelectionJB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileSelectionJBActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(fileTF, javax.swing.GroupLayout.PREFERRED_SIZE, 576, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(fileSelectionJB)
                .addGap(29, 29, 29))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fileSelectionJB)
                    .addComponent(fileTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setPreferredSize(new java.awt.Dimension(704, 50));

        printJB.setText("הדפס");
        printJB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printJBActionPerformed(evt);
            }
        });

        maxNameSizeTF.setText("50");
        maxNameSizeTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                maxNameSizeTFActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(maxNameSizeTF, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 580, Short.MAX_VALUE)
                .addComponent(printJB)
                .addGap(24, 24, 24))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(printJB)
                    .addComponent(maxNameSizeTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);
        getContentPane().add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void maxNameSizeTFActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_maxNameSizeTFActionPerformed
		// TODO add your handling code here:
	}// GEN-LAST:event_maxNameSizeTFActionPerformed

	private void fileSelectionJBActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_fileSelectionJBActionPerformed
		String lastDir = (String) applicationConfiguration.getConfigObject("last.dir");
		if(lastDir != null) {
			FileChooserUtils.setLastSelectedDir(new File(lastDir));
		}
		File f = FileChooserUtils.selectFile(this);
		if (f != null) {
			selectedFile = f;
			applicationConfiguration.saveConfigObject("last.dir", f.getParent());
			processFileSelected();
		}
	}// GEN-LAST:event_fileSelectionJBActionPerformed

	void processFileSelected() {
		jTabbedPane1.removeAll();
		fileTF.setText(selectedFile.getAbsolutePath());
		OrderInTheHouse ord = new OrderInTheHouse();
		try {
			ord.processArchive(new de.schlichtherle.io.File(fileTF.getText()));
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		Collection<String> flightNames = ord.getFlightNames();
		jtas.clear();
		for (String fname : flightNames) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			PrintStream ps = new PrintStream(baos);
			ord.printFlight(fname, ps, Integer.parseInt(maxNameSizeTF.getText()));
			JTextArea jta = new JTextArea(baos.toString());
			jta.setFont(new java.awt.Font("DejaVu Sans Mono", 0, 11));
			jtas.add(jta);
			jTabbedPane1.addTab(fname, new JScrollPane(jta));
		}
	}

	private void printJBActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_printJBActionPerformed
		int tabCount = jTabbedPane1.getTabCount();
		for (int i = 0; i < tabCount; i++) {
			JTextArea jta = jtas.get(i);
			print(jta.getText());
		}

	}// GEN-LAST:event_printJBActionPerformed

	void print2(String s) {
		JobAttributes theJobAttribs = new JobAttributes();
		PageAttributes thePageAttribs = new PageAttributes();

		theJobAttribs.setDialog(JobAttributes.DialogType.NONE);
		// theJobAttribs.setPrinter("HP DeskJet 610C"); // the printer to be
		// used
		PrintJob myJob = getToolkit().getPrintJob(this, "PrintJob", theJobAttribs, thePageAttribs);
		if (myJob != null) {
			Graphics g = myJob.getGraphics();

			if (g != null) {
				// printText(myJob, g, s);
				g.dispose();
			}
			myJob.end();
		}
	}

	void print(String s) {
		try {
			JTextArea jta = new JTextArea(s);
			System.out.println(">>> " + System.getProperty("os.name"));
			if (System.getProperty("os.name").toLowerCase().startsWith("wind")) {
				System.out.println("WIN");
				jta.setFont(new java.awt.Font("DejaVu Sans Mono", 0, 8));
			} else {
				jta.setFont(new java.awt.Font("DejaVu Sans Mono", 0, 8));
			}
			boolean complete = jta.print();
			if (complete) {
			} else {
			}
		} catch (PrinterException pe) {
			pe.printStackTrace();
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/*
		 * Set the Nimbus look and feel
		 */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
					.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(LeGrandFrame.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(LeGrandFrame.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(LeGrandFrame.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(LeGrandFrame.class.getName()).log(
					java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/*
		 * Create and display the form
		 */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				LeGrandFrame f = new LeGrandFrame();
				WindowUtils.setWindowSize(f, .8, .5);
				WindowUtils.centerWindow(f);
				f.setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton fileSelectionJB;
    private javax.swing.JTextField fileTF;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField maxNameSizeTF;
    private javax.swing.JTextArea outputTA;
    private javax.swing.JButton printJB;
    // End of variables declaration//GEN-END:variables
}
